/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.security.validate2;

import cn.nkpro.elcube.basic.Constants;
import cn.nkpro.elcube.data.redis.RedisSupport;
import cn.nkpro.elcube.platform.gen.UserAccountSecret;
import cn.nkpro.elcube.security.UserAccountService;
import cn.nkpro.elcube.security.bo.UserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 根据手机验证码获取token
 * Created by bean on 2019/12/30.
 */
@Component
@Slf4j
@Order(2002)
public class NkLoginMessageVerCodeAuthenticationFilter extends GenericFilterBean implements AuthenticationFilterV2 {

    @Autowired
    private AuthenticationUtils authenticationUtils;
    @Autowired
    private UserAccountService accountService;
    @Autowired
    protected RedisSupport<String> redisSupport;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {

                // 区分客户端
                String client    = authenticationUtils.obtainParam(request, "elcube-client");
                String phone     = authenticationUtils.obtainParam(request, "elcube-phone");
                String verKey    = authenticationUtils.obtainParam(request, "elcube-verkey");
                String verCode   = authenticationUtils.obtainParam(request, "elcube-vercode");

                if (StringUtils.isNoneBlank(client, phone, verKey, verCode)) {
                    String cache = redisSupport.get(Constants.CACHE_TEMP_SMS + verKey);

                    if(StringUtils.equals(cache,verCode)){
                        UserAccountSecret accountSecret = accountService.getAccountSecretByCode("phone", phone);

                        if(accountSecret!=null){

                            UserDetails details = accountService.loadUserById(accountSecret.getAccountId());
                            AuthenticationUtils.simpleValidate(details);
                            AbstractAuthenticationToken auth = new UsernamePasswordAuthenticationToken(details.getUsername(),null, details.getAuthorities());
                            auth.setDetails(details);

                            ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_OK);
                            response.setCharacterEncoding("utf-8");
                            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                            PrintWriter printWriter = response.getWriter();
                            printWriter.print(authenticationUtils.grantToken(client, details.getUsername()));
                            printWriter.flush();
                            printWriter.close();
                            return;
                        }else{
                            authenticationUtils.commence((HttpServletResponse)response, new BadCredentialsException("手机号尚未注册"));
                            return;
                        }
                    }
                    authenticationUtils.commence((HttpServletResponse)response, new BadCredentialsException("验证码错误"));
                    return;
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
